package tests.jdl.synchronization;

import java.sql.Connection;
import java.sql.DriverManager;

import jdl.databaseObjects.DbField;
import jdl.databaseObjects.FieldCollection;
import jdl.databaseObjects.Table;
import jdl.databaseObjects.datatypes.postgreSql.PostgreSqlDbTypeFactory;
import jdl.synchronization.DbObjectNotFoundException;
import jdl.synchronization.PostgreSqlSynchronizer;
import jdl.synchronization.SynchronizationException;
import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class PostgreSqlSynchronizer_Test {
	private PostgreSqlSynchronizer synchronizer;

	@Before
	public void setUp() throws Exception {
		Connection connection = DriverManager.getConnection(
				"jdbc:postgresql://localhost/pagila", "postgres", "123456");
		synchronizer = new PostgreSqlSynchronizer(connection);
	}

	@Test
	public void synchronizeField_checkDbType() throws Exception {
		Table table = new Table("city");
		DbField field = new DbField("country_id",
				PostgreSqlDbTypeFactory.createIntegerDbType());
		table.addField(field);
		synchronizer.synchronizeField(field);
		Assert.assertEquals(PostgreSqlDbTypeFactory.createInt2DbType(),
				field.getDbType());
	}

	@Test(expected = DbObjectNotFoundException.class)
	public void synchronizeField_fieldDoesNotExist() throws Exception {
		Table table = new Table("actor");
		DbField field = new DbField("hello_world",
				PostgreSqlDbTypeFactory.createIntegerDbType());
		table.addField(field);
		synchronizer.synchronizeField(field);
	}

	@Test
	public void synchronizeFieldCollection() throws SynchronizationException {
		Table table = new Table("actor");
		FieldCollection fieldCollection = table.getFieldCollection();
		synchronizer.synchronizeFieldCollection(fieldCollection);
		Assert.assertEquals(4, fieldCollection.getCount());

		DbField field = fieldCollection.getFieldByName("actor_id");
		Assert.assertEquals(PostgreSqlDbTypeFactory.createInt4DbType(),
				field.getDbType());

		field = fieldCollection.getFieldByName("first_name");
		Assert.assertEquals(PostgreSqlDbTypeFactory.createVarcharDbType(45),
				field.getDbType());

		field = fieldCollection.getFieldByName("last_name");
		Assert.assertEquals(PostgreSqlDbTypeFactory.createVarcharDbType(45),
				field.getDbType());

		field = fieldCollection.getFieldByName("last_update");
		Assert.assertEquals(PostgreSqlDbTypeFactory.createTimestampDbType(),
				field.getDbType());
	}
}